package com.mobile.service.impl.system;

import com.github.pagehelper.PageInfo;
import com.mobile.service.dao.DaoSupport;
import com.mobile.service.dto.DataDictionaryDTO;
import com.mobile.service.dto.DataDictionaryQueryDTO;
import com.mobile.service.dto.UserDTO;
import com.mobile.service.inter.system.DictService;
import com.mobile.service.util.PageUtils;
import com.mobile.util.*;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 权限管理service实现类
 */
@Service("dictService")
@Transactional
public class DictServiceImpl implements DictService {
    @Resource(name = "daoSupport")
    private DaoSupport dao;

    /**
     * 数据字典列表（分页）
     * @param dictionaryQueryDTO
     * @return
     */
    @SuppressWarnings("unchecked")
    @Override
    public PageResult<DataDictionaryDTO> getDictListPage(DataDictionaryQueryDTO dictionaryQueryDTO) throws Exception {
        PageUtils.startPage(dictionaryQueryDTO);
        List<DataDictionaryDTO> dictList = (List<DataDictionaryDTO>) dao.findForList("DictMapper.dictlistPage", dictionaryQueryDTO);
        //查询字典项名称、字典项值
        for (DataDictionaryDTO dict : dictList) {
            List<DataDictionaryDTO> dictItem = (List<DataDictionaryDTO>) dao.findForList("DictMapper.getDictItemByNo", dict);
            dict.setDictItem(dictItem);
        }
        PageUtils.clearPage();
        // 封装结果
        return new PageResult<>(dictList);
    }

    /**
     * 根据字典ID查询
     * @param dicNo
     * @return
     */
    @Override
    public PageData getDictByNo(String dicNo) throws Exception {
        return (PageData) dao.findForObject("DictMapper.getDictByNo", dicNo);
    }

    /**
     * 添加字典
     * @param pd
     * @return
     */
    @Override
    public Map<String, Object> addDict(PageData pd) throws Exception {
        Map<String, Object> map = new HashMap<>();
        String dicNo = pd.getString("dicNo");

        //验证字典类型是否是空字符串
        if (StringUtil.isEmpty(dicNo)) {
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_FAILED);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0007", "字典类型"));
            return map;
        }

        //验证字典ID是否重复
        Object obj = dao.findForObject("DictMapper.getDictByNo", dicNo);
        if (null != obj) {
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_FAILED);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0004", "该字典类型"));
            return map;
        }

        dao.save("DictMapper.insertDict", pd);
        map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);
        map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("I0011"));
        return map;
    }

    /**
     * 修改字典
     * @param pd
     * @return
     */
    @Override
    public Map<String, Object> updateDict(PageData pd) throws Exception {
        Map<String, Object> map = new HashMap<>();
        String dicNo = pd.getString("dicNo");

        //验证字典类型是否是空字符串
        if (StringUtil.isEmpty(dicNo)) {
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_FAILED);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0007", "字典类型"));
            return map;
        }

        PageData data = this.getDictByNo(dicNo);
        if (Objects.isNull(data)) {
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_FAILED);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0001"));
            return map;
        }

        dao.update("DictMapper.updateDict", pd);
        map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);
        map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("I0009"));
        return map;
    }

    /**
     * 删除字典
     * @param pd
     * @return
     */
    @SuppressWarnings("unchecked")
    @Override
    public Map<String, Object> removeDict(PageData pd) throws Exception {
        Map<String, Object> map = new HashMap<>();
        String dicNo = pd.getString("dicNo");

        //验证要删除的字典是否有字典值
        List<PageData> dictItems = (List<PageData>) dao.findForList("DictMapper.getDictItemByNo", dicNo);
        if (!CollectionUtils.isEmpty(dictItems)) {
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_FAILED);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0025"));
            return map;
        }

        dao.delete("DictMapper.deleteDict", dicNo);
        map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);
        map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("I0010"));
        return map;
    }

    /**
     * 添加字典项
     * @param pd
     * @return
     */
    @Override
    public Map<String, Object> addDictItem(PageData pd) throws Exception {
        Map<String, Object> map = new HashMap<>();
        String dicNo = pd.getString("dicNo");
        String newDicValue = pd.getString("newDicValue");

        //验证字典项值是否是空字符串
        if (StringUtil.isEmpty(newDicValue)) {
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_FAILED);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0007", "字典项值"));
            return map;
        }

        //验证该字典项值是否已经存在
        int count = (int) dao.findForObject("DictMapper.getDictItemCount", pd);
        if (count > 0) {
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_FAILED);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0004", "该字典项值"));
            return map;
        }

        //empty == null，该字典项存在，字典项值为空，修改该字典项，否则添加字典项
        List<PageData> empty = (List<PageData>) dao.findForList("DictMapper.dicValueIsEmpty", dicNo);
        if (CollectionUtils.isEmpty(empty)) {
            pd.put("dicValue", "");
            dao.update("DictMapper.updateDictItem", pd);
        } else {
            pd.put("dicValue", newDicValue);
            pd.put("dicDescription", empty.get(0).getString("dicDescription"));
            dao.save("DictMapper.insertDictItem", pd);
        }

        map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);
        map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("I0011"));
        return map;
    }

    /**
     * 根据字典ID和字典项值查询字典项
     * @param pd
     * @return
     */
    @Override
    public PageData getDictItemByNoAndValue(PageData pd) throws Exception {
        return (PageData) dao.findForObject("DictMapper.getDictItemByNoAndValue", pd);
    }

    /**
     * 修改字典项
     * @param pd
     * @return
     */
    @Override
    public Map<String, Object> updateDictItem(PageData pd) throws Exception {
        Map<String, Object> map = new HashMap<>();
        String newDicValue = pd.getString("newDicValue");

        //验证字典项值是否是空字符串
        if (StringUtil.isEmpty(newDicValue)) {
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_FAILED);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0007", "字典项值"));
            return map;
        }

        PageData parms = new PageData();
        parms.put("dicNo", pd.getString("dicNo"));
        parms.put("dicValue", pd.getString("dicValue"));
        PageData dictItem = this.getDictItemByNoAndValue(parms);
        if (Objects.isNull(dictItem)) {
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_FAILED);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0001"));
            return map;
        }

        parms.put("dicNo", pd.getString("dicNo"));
        parms.put("dicValue", newDicValue);
        dictItem = this.getDictItemByNoAndValue(parms);
        //验证该字典项值是否已经存在
        if (null != dictItem && !pd.getString("dicValue").equals(newDicValue)) {
            map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_FAILED);
            map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("E0004", "该字典项值"));
            return map;
        }

        dao.update("DictMapper.updateDictItem", pd);
        map.put(Const.ACTION_RESULT, Const.ACTION_RESULT_SUCCESS);
        map.put(Const.ACTION_MESSAGE, MessageUtil.getMessage("I0009"));
        return map;
    }

    /**
     * 删除字典项
     * @param pd
     */
    @Override
    public void removeDictItem(PageData pd) throws Exception {
        int count = (int) dao.findForObject("DictMapper.getDictCount", pd.getString("dicNo"));
        //如果要删除的字典项还剩一条，更新字典项值为空
        if (count == 1) {
            pd.put("newDicValue", "");
            pd.put("dicDisplayName", "");
            dao.update("DictMapper.updateDictItem", pd);
        } else {
            dao.delete("DictMapper.deleteDictItem", pd);
        }
    }

    /**
     * 根据字典ID查询所有字典项值
     * @param dicNo
     * @return
     */
    @Override
    public List<PageData> getDictItemByNo(String dicNo) throws Exception {
        return (List<PageData>) dao.findForList("DictMapper.getDictItemByNo", dicNo);
    }

    /**
     * 根据字典ID查询所有字典项值(前端用)
     * @param dicNo
     * @return
     */
    @Override
    public List<PageData> getDictItemByNoPre(String dicNo) throws Exception {
        return (List<PageData>) dao.findForList("DictMapper.getDictItemByNoPre", dicNo);
    }

    /**
     * 根据字典ID和拓展字段4查询所有字典项值
     * @param pd
     * @return
     * @throws Exception
     */
    @Override
    public List<PageData> getDictItemByNoAndExtendFour(PageData pd) throws Exception {
        return  (List<PageData>) dao.findForList("DictMapper.getDictItemByNoAndExtendFour", pd);
    }
}
